var vscode = require("vscode");
var path = require("path");
var fs = require("fs");
var Sass = require("./sass/sass.sync.js");
var autoprefixer = require('autoprefixer');
var postcss      = require('postcss');
function error(msg){
    vscode.window.showErrorMessage(msg);
}
class Compiler{
    constructor(document) {
        this.document = document;
        var sassFilenamePath = path.parse(this.document.fileName);
        this.path = sassFilenamePath;
    }

    getOptions(code){
        var commentMatch = /^\s*\/\/\s*(.+)/.exec(code);
        var option = {};
        if(commentMatch){
            try{
                option = JSON.parse("{"+commentMatch[1]+"}");
            }catch(e){
                option = {};
            }
        }
        return option;
    }

    readFile(filename, callback){
        fs.readFile(filename, (err, buffer)=>{
            if(!err){
                var code = buffer.toString();
                var option = this.getOptions(code);
                if(option.main){
                    this.readFile(path.normalize(this.path.dir+path.sep+option.main), callback);
                }else if(option.out){
                    callback(code, option);
                }
            }
        });
    }

    writeFile(filename, content, callback){
        this.mkdirsSync(path.dirname(filename));
        fs.writeFile(filename, content, (err)=>{
            err ? error(err) : callback();
        });
    }

    mkdirsSync(dirpath){
        if (!fs.existsSync(dirpath)) {
            var pathtmp;
            dirpath.split(path.sep).forEach(function(dirname) {
                pathtmp = pathtmp ? path.join(pathtmp, dirname) : dirname;
                fs.existsSync(pathtmp) || fs.mkdirSync(pathtmp);
            });
        }
        return true; 
    }

    execute(){
        this.readFile(this.document.fileName, (code, option)=>{
            var style = 
            Sass.compile(code, {
                // nested, expanded, compact, compressed
                // default: expanded
                style: (option.style&&["nested", "expanded", "compact", "compressed"].indexOf(option.style)>=0) 
                       ? Sass.style[option.style] 
                       : Sass.style.expanded
            }, (result)=>{
                if(result.status){
                    error(result.message);
                }else{
                    var output = path.normalize(this.path.dir+path.sep+option.out);
                    if(option.autoprefixer){
                        var browsers = option.autoprefixer===true?["last 2 versions", "Firefox >= 20", "iOS 7", "> 5%"]:option.autoprefixer;
                        postcss([ autoprefixer({ browsers: browsers }) ]).process(result.text).then((res)=>{
                            res.warnings().forEach((warn)=>{
                                vscode.window.showWarningMessage(warn.toString());
                            });
                            result.text = res.css;
                            this.writeFile(output, result.text, ()=>{
                                vscode.window.setStatusBarMessage("已经编译至 "+output, 1500);
                            });
                        });
                    }else{
                        this.writeFile(output, result.text, ()=>{
                            vscode.window.setStatusBarMessage("已经编译至 "+output, 1500);
                        });
                    }
                }
            });
        });
    }
}

module.exports = Compiler;